# **********************OBJ INFO**************************
# Author:YuKalix
# @Time    : 2019-9-19 16:15
# @Site    : 52ziyu.cn
# @File    : test.py
# @software: PyCharm
# *********************************************************

import requests
from urllib import parse

from time import sleep
import json
import time
import random


class SpiderImages:
    def __init__(self, key='邓伦'):
        self.key = key
        self.url = 'https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord={0}' \
                   '&cl=&lm=&ie=utf-8&oe=utf-8&adpicid=&st=&z=&ic=&hd=&latest=&copyright=&word={1}' \
                   '&s=&se=&tab=&width=&height=&face=&istype=&qc=&nc=&fr=&expermode=&force=&pn='.format(key, key)

    def request(self, url):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0',
        }
        response = requests.get(url, headers=headers)
        return response

    def read_and_download(self):
        all_images_url_list = []
        # 获取今天的文件
        f = open('./{}.txt'.format((parse.unquote(self.key))), 'r')
        for line in f:
            all_images_url_list.append(line.replace('\n', ''))
        f.close()
        download_path = random.choice(all_images_url_list)
        self.download(download_path)


    def download(self, item):
        sleep(0.1)
        file_name = '1.jpg'
        try:
            content = requests.get(item).content
            with open(file_name, 'wb')as f:
                f.write(content)
        except:
            print('下载失败:', item)

def spider_main():
    S = SpiderImages()
    S.read_and_download()


if __name__ == '__main__':
    pass